package com.eedi.framework.oauth2.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.google.common.annotations.VisibleForTesting;
import com.eedi.framework.common.enums.CommonStatusEnum;
import com.eedi.framework.common.enums.UserTypeEnum;
import com.eedi.framework.common.exception.util.ServiceExceptionUtil;
import com.eedi.framework.common.pojo.PageResult;
import com.eedi.framework.common.util.object.BeanUtils;
import com.eedi.framework.common.util.string.StrUtils;
import com.eedi.framework.oauth2.controller.org.vo.client.OrgOAuth2ClientPageReqVO;
import com.eedi.framework.oauth2.controller.org.vo.client.OrgOAuth2ClientSaveReqVO;
import com.eedi.framework.oauth2.dal.OrgOauth2CacheKeyConstants;
import com.eedi.framework.oauth2.dal.dataobject.OrgOAuth2ClientDO;
import com.eedi.framework.oauth2.dal.mapper.OrgOAuth2ClientMapper;
import com.eedi.framework.oauth2.enums.OrgOauth2ErrorCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * OAuth2.0 Client Service 实现类
 *
 * @author 永聚长青源码
 */
@Service
@Validated
@Slf4j
public class OrgOAuth2ClientServiceImpl implements OrgOAuth2ClientService {

    @Resource
    private OrgOAuth2ClientMapper orgOauth2ClientMapper;

    @Override
    public String createOAuth2Client(OrgOAuth2ClientSaveReqVO createReqVO) {
        validateClientCodeExists(null, createReqVO.getClientCode());
        // 插入
        OrgOAuth2ClientDO client = BeanUtils.toBean(createReqVO, OrgOAuth2ClientDO.class);
        orgOauth2ClientMapper.insert(client);
        return client.getOrgOauth2ClientId();
    }

    @Override
    public String getClientIdByOrginfoId(String orgInfoId) {
        return orgOauth2ClientMapper.getSysClientIdByOrgInfoId(orgInfoId);
    }

    @Override
    public String getClientIdByOrgInfoIdAndUserType(String orgInfoId, UserTypeEnum userTypeEnum) {
        return orgOauth2ClientMapper.getSysClientIdByOrgInfoIdAndUserType(orgInfoId,userTypeEnum);
    }

    @Override
    @CacheEvict(cacheNames = OrgOauth2CacheKeyConstants.ORG_OAUTH_CLIENT,
            allEntries = true) // allEntries 清空所有缓存，因为可能修改到 clientId 字段，不好清理
    public void updateOAuth2Client(OrgOAuth2ClientSaveReqVO updateReqVO) {
        // 校验存在
        validateOAuth2ClientExists(updateReqVO.getOrgOauth2ClientId());
        // 校验 Client 未被占用
        validateClientCodeExists(updateReqVO.getOrgOauth2ClientId(), updateReqVO.getClientCode());

        // 更新
        OrgOAuth2ClientDO updateObj = BeanUtils.toBean(updateReqVO, OrgOAuth2ClientDO.class);
        orgOauth2ClientMapper.updateById(updateObj);
    }

    @Override
    @CacheEvict(cacheNames = OrgOauth2CacheKeyConstants.ORG_OAUTH_CLIENT,
            allEntries = true) // allEntries 清空所有缓存，因为 id 不是直接的缓存 key，不好清理
    public void deleteOAuth2Client(String orgOauth2ClientId) {
        // 校验存在
        validateOAuth2ClientExists(orgOauth2ClientId);
        // 删除
        orgOauth2ClientMapper.deleteById(orgOauth2ClientId);
    }

    private void validateOAuth2ClientExists(String orgOauth2ClientId) {
        if (orgOauth2ClientMapper.selectById(orgOauth2ClientId) == null) {
            throw ServiceExceptionUtil.exception(OrgOauth2ErrorCodeConstants.ORG_OAUTH2_CLIENT_NOT_EXISTS);
        }
    }

    @VisibleForTesting
    void validateClientCodeExists(String orgOauth2ClientId, String clientCode) {
        OrgOAuth2ClientDO client = orgOauth2ClientMapper.selectByClientCode(clientCode);
        if (client == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的客户端
        if (StrUtil.isEmpty(orgOauth2ClientId)) {
            throw ServiceExceptionUtil.exception(OrgOauth2ErrorCodeConstants.ORG_OAUTH2_CLIENT_EXISTS);
        }
        if (!client.getOrgOauth2ClientId().equals(orgOauth2ClientId)) {
            throw ServiceExceptionUtil.exception(OrgOauth2ErrorCodeConstants.ORG_OAUTH2_CLIENT_EXISTS);
        }
    }

    @Override
    public OrgOAuth2ClientDO getOAuth2Client(String orgOauth2ClientId) {
        return orgOauth2ClientMapper.selectById(orgOauth2ClientId);
    }

    @Override
    @Cacheable(cacheNames = OrgOauth2CacheKeyConstants.ORG_OAUTH_CLIENT, key = "#clientCode",
            unless = "#result == null")
    public OrgOAuth2ClientDO getOAuth2ClientFromCache(String clientCode) {
        return orgOauth2ClientMapper.selectByClientCode(clientCode);
    }

    @Override
    public PageResult<OrgOAuth2ClientDO> getOAuth2ClientPage(OrgOAuth2ClientPageReqVO pageReqVO) {
        return orgOauth2ClientMapper.selectPage(pageReqVO);
    }

    @Override
    public OrgOAuth2ClientDO validOAuthClientFromCache(String clientCode, String clientSecret, String authorizedGrantType,
                                                       Collection<String> scopes, String redirectUri) {
        // 校验客户端存在、且开启
        OrgOAuth2ClientDO client = getSelf().getOAuth2ClientFromCache(clientCode);
        if (client == null) {
            throw ServiceExceptionUtil.exception(OrgOauth2ErrorCodeConstants.ORG_OAUTH2_CLIENT_NOT_EXISTS);
        }
        if (CommonStatusEnum.isDisable(client.getStatus().getCode())) {
            throw ServiceExceptionUtil.exception(OrgOauth2ErrorCodeConstants.ORG_OAUTH2_CLIENT_DISABLE);
        }

        // 校验客户端密钥
        if (StrUtil.isNotEmpty(clientSecret) && ObjectUtil.notEqual(client.getSecret(), clientSecret)) {
            throw ServiceExceptionUtil.exception(OrgOauth2ErrorCodeConstants.ORG_OAUTH2_CLIENT_CLIENT_SECRET_ERROR);
        }
        // 校验授权方式
        if (StrUtil.isNotEmpty(authorizedGrantType) && !CollUtil.contains(client.getAuthorizedGrantTypes(), authorizedGrantType)) {
            throw ServiceExceptionUtil.exception(OrgOauth2ErrorCodeConstants.ORG_OAUTH2_CLIENT_AUTHORIZED_GRANT_TYPE_NOT_EXISTS);
        }
        // 校验授权范围
        if (CollUtil.isNotEmpty(scopes) && !CollUtil.containsAll(client.getScopes(), scopes)) {
            throw ServiceExceptionUtil.exception(OrgOauth2ErrorCodeConstants.ORG_OAUTH2_CLIENT_SCOPE_OVER);
        }
        // 校验回调地址
        if (StrUtil.isNotEmpty(redirectUri) && !StrUtils.startWithAny(redirectUri, client.getRedirectUris())) {
            throw ServiceExceptionUtil.exception(OrgOauth2ErrorCodeConstants.ORG_OAUTH2_CLIENT_REDIRECT_URI_NOT_MATCH, redirectUri);
        }
        return client;
    }

    /**
     * 获得自身的代理对象，解决 AOP 生效问题
     *
     * @return 自己
     */
    private OrgOAuth2ClientServiceImpl getSelf() {
        return SpringUtil.getBean(getClass());
    }

}
